package com.mz.wlm.utils;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.OSSResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.mz.wlm.bean.SendMissonBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 上传图片到阿里云OSS
 */
public class MyOSSUtils {

    private static MyOSSUtils instance;

    /**
     * 主机地址（根据地区而变化）
     */

    private final String P_ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";
    private final String P_BUCKETNAME = "wanlemiao";

    /**
     * （服务器域名，后台给）
     */

//    private final String P_STSSERVER = "wanlemiao.oss-cn-hangzhou.aliyuncs.com";


    private OSS oss;

    private SimpleDateFormat simpleDateFormat;
    /**
     * （文件夹名字，与后台统一）
     */
    private final String OBJECT_NAME = "logo";
    private OSSStsTokenCredentialProvider credetialProvider;
    private ClientConfiguration conf;

    public MyOSSUtils() {

    }

    public static MyOSSUtils getInstance() {

        if (instance == null) {
            if (instance == null) {
                return new MyOSSUtils();
            }

        }
        return instance;
    }

    private void getOSs(Context context) {
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
        OSSCredentialProvider provider = OSSConfig.newCustomSignerCredentialProvider();
//      ClientConfiguration conf = new ClientConfiguration();
// OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(P_STSSERVER);

//该配置类如果不设置，会有默认配置，具体可看该类

        conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000);// 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000);// socket超时，默认15秒
        conf.setMaxConcurrentRequest(5);// 最大并发请求数，默认5个

        conf.setMaxErrorRetry(2);// 失败后最大重试次数，默认2次

        oss = new OSSClient(context, P_ENDPOINT, provider);

        if (simpleDateFormat == null) {
            simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        }

    }

    /**
     * 上传图片 上传文件
     *
     * @param context         application上下文对象
     * @param ossUpCallback 成功的回调
     * @param img_name        上传到oss后的文件名称，图片要记得带后缀 如：.jpg
     * @param imgPath         图片的本地路径
     */

    public void upImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final String img_name, String imgPath) {
        getOSs(context);
//
        PutObjectRequest putObjectRequest = new PutObjectRequest(P_BUCKETNAME, OBJECT_NAME + "/" + img_name, imgPath);

        // 异步上传时可以设置进度回调。
        putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);

            }

        });

        OSSAsyncTask task = oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Log.d("PutObject", "UploadSuccess");

                Log.d("ETag", result.getETag());

                Log.d("RequestId", result.getRequestId());

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。

                    clientExcepion.printStackTrace();
                }

                if (serviceException != null) {

                    Log.e("ErrorCode", serviceException.getErrorCode());

                    Log.e("RequestId", serviceException.getRequestId());

                    Log.e("HostId", serviceException.getHostId());

                    Log.e("RawMessage", serviceException.getRawMessage());

                }
            }

        });

        oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {

            @Override

            public void onSuccess(OSSRequest request, OSSResult result) {

                Log.e("MyOSSUtils", "------getRequestId:" + result.getRequestId());

                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME, OBJECT_NAME + "/" + img_name));

            }

            @Override

            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
                Log.e("MyOSSUtils", "------onFailure:" + clientException.getMessage());
                ossUpCallback.successImg(null);

            }
        });

    }

    /**
     * 上传图片 上传流
     *
     * @param context         application上下文对象
     * @param ossUpCallback 成功的回调
     * @param         上传到oss后的文件名称，图片要记得带后缀 如：.jpg
     * @param               图片的byte数组
     */

  /*  public void upImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final String img_name, byte[] imgbyte) {

        getOSs(context);
        final Date data = new Date();

        data.setTime(System.currentTimeMillis());

        PutObjectRequest putObjectRequest = new PutObjectRequest(P_BUCKETNAME, simpleDateFormat.format(data) + "/" + img_name, imgbyte);

        putObjectRequest.setProgressCallback(new OSSProgressCallback() {

            @Override
            public void onProgress(Object request, long currentSize, long totalSize) {

                ossUpCallback.inProgress(currentSize, totalSize);

            }


        });

        oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {

            @Override

            public void onSuccess(OSSRequest request, OSSResult result) {

                ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME, simpleDateFormat.format(data) + "/" + img_name));

            }

            @Override
            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {

                ossUpCallback.successImg(null);

            }

        });

    }*/
    public void upMulitImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback,  List<SendMissonBean> imgList) {
        getOSs(context);
        LogUtil.getInstance().e("ossload start"+new Gson().toJson(imgList));
        OSSCredentialProvider provider = OSSConfig.newCustomSignerCredentialProvider();
        OSSClient oss = new OSSClient(context, P_ENDPOINT, provider, conf);
        for (int i = 0; i < imgList.size(); i++) {
            String path = imgList.get(i).getBmpPath();
            String name = imgList.get(i).getName();
            LogUtil.getInstance().e("ossload name"+name);
            //开始上传工作
            PutObjectRequest put = new PutObjectRequest(P_BUCKETNAME, OBJECT_NAME + "/" + name, path);
            // 异步上传时可以设置进度回调。
            put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                    callBack.progress((int) (((double) currentSize / (double) totalSize) * 100));
                }
            });
            oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    LogUtil.getInstance().e("ossload result"+name);
                    ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME, OBJECT_NAME + "/" +name));
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
//                    callBack.failure();
                }
            });
        }
    }

    public void upVideo(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final String video_name, String video_path) {

        getOSs(context);

        final Date data = new Date();

        data.setTime(System.currentTimeMillis());

        PutObjectRequest putObjectRequest = new PutObjectRequest(P_BUCKETNAME, simpleDateFormat.format(data) + "/" + video_name, video_path);

        putObjectRequest.setProgressCallback(new OSSProgressCallback() {

            @Override

            public void onProgress(Object request, long currentSize, long totalSize) {

                ossUpCallback.inProgress(currentSize, totalSize);

            }

        });

        oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {

            @Override

            public void onSuccess(OSSRequest request, OSSResult result) {

                ossUpCallback.successVideo(oss.presignPublicObjectURL(P_BUCKETNAME, simpleDateFormat.format(data) + "/" + video_name));

            }

            @Override

            public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {

                ossUpCallback.successVideo(null);

            }

        });

    }

    public interface OssUpCallback {

        void successImg(String img_url);

        void successVideo(String video_url);

        void inProgress(long progress, long zong);

    }


}
